package com.menggudf.exception;

import com.menggudf.common.RespResult;
import com.mysql.cj.jdbc.exceptions.CommunicationsException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;


/**
 * 全局异常处理
 * @author zengqd
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    public RespResult exceptionHandler(Exception e){
        //e.printStackTrace();

        if(e instanceof BizException){
            return RespResult.fail(((BizException) e).getMsg());
        } else if (e instanceof CommunicationsException) {
            return RespResult.fail("当前访问人数较多，请稍后操作");
        }
        log.error("bizException 异常，参数校验异常：{}", e);
        return RespResult.fail(e.getMessage());
    }

    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public RespResult methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
        String msg = e.getBindingResult().getFieldErrors()
                .stream()
                .map(n -> String.format("%s", n.getDefaultMessage()))
                .reduce((x, y) -> String.format("%s; %s", x, y))
                .orElse("参数输入有误");
        log.error("MethodArgumentNotValidException 异常，参数校验异常：{}", msg);
        return RespResult.fail(msg);
    }
}
